package com.abhimanyu.service;

import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.abhimanyu.service.coziie.jaxb.Table;
import com.abhimanyu.service.coziie.jaxb.Table.Tbody.Tr;
import com.abhimanyu.service.coziie.jaxb.Table.Tbody.Tr.Td;
import com.abhimanyu.service.coziie.jaxb.Table.Tbody.Tr.Td.A;
import com.abhimanyu.service.model.DollarRateServiceData;


public class CoziieDollarRateObserver extends AbstractDollarRateObserver {
	private static final String PARSE_START = "<table class=\"table\"";
	private static final String PARSE_END = "</table>";

	public CoziieDollarRateObserver() {
		super.setUrl("http://www.coziie.com/exchange-rates/usd-inr");
	}

	public List<DollarRateServiceData> getCurrentDollarRate() {
		List<DollarRateServiceData> serviceModelList = null;
		/*DollarRateService serviceModel = new DollarRateService();
		String dollarRate = null;*/
		try {
			String webPageContent = executeDollarService();
			
			String dataTableContent = getDollarRate(webPageContent);
			// System.out.println(dataTableContent);

			serviceModelList = unmarshallarDollarRate(dataTableContent);
			System.out.println("serviceModelList.size()".toUpperCase() + serviceModelList.size());
			// dollarRate = getDollarRate(webPageContent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/*serviceModel.setDollarRateData(dollarRate);
		serviceModelList.add(serviceModel);*/
		return serviceModelList;
	}

	@SuppressWarnings("rawtypes")
	public List<DollarRateServiceData> unmarshallarDollarRate(String dataTableContent)
			throws JAXBException {
		List<DollarRateServiceData> dollarServiceList = new ArrayList<DollarRateServiceData>();
		DollarRateServiceData serviceData = null;
		JAXBContext context = JAXBContext.newInstance(Table.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		// unmarshaller.setProperty("jaxb.encoding", "Unicode");
		dataTableContent = dataTableContent.replaceAll("&nbsp", " ");
		Reader reader = new StringReader(dataTableContent);
		Table table = (Table) unmarshaller.unmarshal(reader);
		// Parsing using the table as shown below
		/**
		 * <table class="table">
		 * 	<tbody>
		 * 		<tr>
		 * 			<td class="service"> 
		 * 				<a href="/exchange-rates/usd-inr/service/49/reserve-bank-of-india-rbi">Reserve Bank Of India (RBI)</a>
		 * 			</td>
		 * 			<td class="rate">60.85</td>
		 * 			<td><span>&nbsp;</span></td>
		 * 			<td>
		 * 				<a href="http://rbi.org.in">Website</a>
		 * 			</td>
		 * 		</tr>
		 * 	</tbody>
		 * </table>
		 */
		
		String dollarRateFromService = null;
		String serviceName = null;
		for (Tr tr : table.getTbody().getTr()) {
			serviceName = "";
			dollarRateFromService = "";
			serviceData = new DollarRateServiceData();
			for (Td td : tr.getTd()) {
				//System.out.println("TD CLASS : " + td.getClazz());
				// Skip the td tags that don't have 'class' attribute
				if (td.getClazz() == null || td.getClazz().length() == 0) {
					continue;
				}
				// Start fetching the dollar data and the service name.
				for (Serializable s : td.getContent()) {				
					if("service".equalsIgnoreCase(td.getClazz())) {
						/*serviceName = ((A) ((JAXBElement) s).getValue())
								.getValue();*/
						if (s instanceof JAXBElement) {

							//System.out.println("TEST : " + (s));
							serviceName = ((A) ((JAXBElement) s).getValue())
									.getValue();
							System.out.println("Service Name : " + serviceName);
							serviceData.setServiceName(serviceName);
						}
						
					} else if("rate".equalsIgnoreCase(td.getClazz())) {
						dollarRateFromService = (String)s;// This will contain the dollar data.
						System.out.println("Dollar Rate : " + dollarRateFromService); 
						serviceData.setDollarRateData(dollarRateFromService);
					}
					
					/*if (s instanceof String && ((String) s).trim().length() > 0)  
					{					
						dollarRateFromService = (String)s;// This will contain the dollar data.
						System.out.println("String : " + dollarRateFromService); 
						serviceData.setDollarRateData(dollarRateFromService);
					} else if (s instanceof JAXBElement) {
						if (((JAXBElement) s).getValue() instanceof A) {
							// This will contain the service name.
							serviceName = ((A) ((JAXBElement) s).getValue())
									.getValue();
							System.out.println("serviceName : " + serviceName);
							serviceData.setServiceName(serviceName);
							// Below commented code will contain the service website address.
							System.out.println("A : "
									+ ((A) ((JAXBElement) s).getValue())
											.getHref());
						}
					}*/
					
				}
			}
			dollarServiceList.add(serviceData);
		}
		System.out.println("dollarServiceList.size()".toUpperCase() + dollarServiceList.size());
		return dollarServiceList;
	}

	private String getDollarRate(String webPageContent) {
		return webPageContent.substring(webPageContent.indexOf(PARSE_START),
				webPageContent.indexOf(PARSE_END) + PARSE_END.length());

	}

	public static void main(String[] args) {
		System.out.println(new CoziieDollarRateObserver()
				.getCurrentDollarRate());
	}

	@Override
	public String toString() {
		return "Coziie";
	}
}
